const { MongoClient, ServerApiVersion } = require('mongodb')
let dayjs = require('dayjs')

// 数据库地址
const uri = 'mongodb://localhost:27017/studenDB'

// 连接数据库
const client = new MongoClient(uri, {
  serverApi: {
    version: ServerApiVersion.v1,
    strict: true,
    deprecationErrors: true,
  },
})

// 查询所有
const quertDataAll = async () => {
  try {
    await client.connect()
    // 获取数据库对象
    const db = client.db('studenDB')
    // 获取student_info表
    const studentInfoDb = db.collection('student_info')
    const res = await studentInfoDb.find().toArray()
  } catch (error) {
    console.dir(error)
  } finally {
    client.close()
  }
}

// 用户登录查询
const userLogin = async (account, password) => {
  try {
    await client.connect()
    // 获取数据库对象
    const db = client.db('studenDB')
    // 获取student_info表
    const studentInfoDb = db.collection('student_info')
    const res = await studentInfoDb.findOne(account, password)
    if (res) {
      return { msg: '登录成功', time: dayjs().format('YYYY-MM-DD HH:mm:ss') }
    } else {
      return {
        msg: '账号或者密码错误',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      }
    }
  } catch (error) {
    return {
      msg: '服务器异常',
    }
  } finally {
    client.close()
  }
}

// 用户注册
const userRegistration = async (data) => {
  try {
    await client.connect()
    // 获取数据库对象
    const db = client.db('studenDB')
    // 获取student_info表
    const studentInfoDb = db.collection('student_info')
    // 查询手机号，账号是否被注册
    const query = {
      $or: [
        {
          account: data.account,
          phone: data.phone,
        },
      ],
    }
    const res = await studentInfoDb.findOne({
      $or: [{ account: data.account }, { role: data.phone }],
    })
    if (!res) {
      await studentInfoDb.insertOne({ role: 'user', ...data })
      return { msg: '注册成功', time: dayjs().format('YYYY-MM-DD HH:mm:ss') }
    } else {
      return {
        msg: '用户手机号或用户名已存在',
        time: dayjs().format('YYYY-MM-DD HH:mm:ss'),
      }
    }
  } catch (error) {
  } finally {
    client.close()
  }
}
module.exports = { quertDataAll, userLogin, userRegistration }
